﻿using HttpWebApiTest.Common;
using HttpWebApiTest.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;


namespace HttpWebApiTest.Services
{
    /// <summary>
    /// 方式2：命名式使用方式
    /// 在注册时做好配置，使用时不就用再配置了,比如：
    /// var client = _httpClientFactory.CreateClient("myapi");\
    /// 
    /// MultipartFormDataContent=》multipart/form-data
    /// FormUrlEncodedContent=》application/x-www-form-urlencoded
    //    StringContent =》application/json等
    //    StreamContent =》binary
    /// </summary>
    public class HttpClientService2
    {
        /// <summary>
        /// 注入HttpClientFactory
        /// </summary>
        /// <param name="httpClientFactory"></param>
        public HttpClientService2(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        IHttpClientFactory _httpClientFactory;

        /// <summary>
        /// 从远API获取用户信息
        /// get http://localhost:5000/api/user/yus/12
        /// </summary>
        /// <returns></returns>
        public string GetInfoRemote()
        {
            //创建命名的HttpClient
            var client = CreateNamedClient();
            //HttpClientr默认配置已在注册服务时配置好了

            var url = "/api/user/yus/12";
            //var url = "http://localhost:5000/api/user/yus/12";

            //Get url
            string result = client.GetStringAsync(url).Result;
            return result;
        }

        /// <summary>
        /// 向远程服务器提交数据
        /// post http://localhost:5000/api/setuser
        /// </summary>
        /// <returns></returns>
        public string SetInfoRemote()
        {
            //创建命名的HttpClient
            var client = CreateNamedClient();
            //HttpClientr默认配置已在注册服务时配置好了

            //构造要提交数据
            var httpContent = new JsonContent(InputMode.Build());
            //或
            //var json = JsonConvert.SerializeObject(InputMode.Build());
            //var httpContent = new StringContent(json, Encoding.UTF8, "application/json");

            var url = "/api/setuser";
            //var url = "http://localhost:5000/api/user/yus/12";

            //Post Url
            var response = client.PostAsync(url, httpContent).Result;
            if (response.IsSuccessStatusCode)
            {
                return response.Content.ReadAsStringAsync().Result;
            }
            else
            {
                return response.ToString();
            }
        }

        /// <summary>
        /// 创建命名的HttpClient
        /// </summary>
        /// <returns></returns>
        private HttpClient CreateNamedClient()
        {
            string httpClientName = "myapi";
            return _httpClientFactory.CreateClient(httpClientName);
        }

    }
}
